use crate::{Solution, SolutionPair};
use std::fs::read_to_string;

///////////////////////////////////////////////////////////////////////////////

pub fn solve() -> SolutionPair {
    let input = read_to_string("input/day01.txt").unwrap();

    let sol1: String = part1(String::from(&input));
    let sol2: String = part2(String::from(&input));

    (Solution::from(sol1), Solution::from(sol2))
}

fn calc_elf_calories(calories_lines: String) -> Vec<u32> {
    calories_lines
        .split("\n\n")
        .map(|calories| calories.lines().map(|c| c.parse::<u32>().unwrap()).sum())
        .collect()
}

fn part1(calories_lines: String) -> String {
    let elves = calc_elf_calories(calories_lines);

    elves.iter().max().unwrap().to_string()
}

fn part2(calories_lines: String) -> String {
    let mut elves = calc_elf_calories(calories_lines);
    elves.sort_by(|a, b| b.cmp(a));

    elves.iter().take(3).sum::<u32>().to_string()
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::etc::utils;

    #[test]
    fn test_part1() {
        let input = utils::to_multiline_string(vec![
            "1000", "2000", "3000", "", "4000", "", "5000", "6000", "", "7000", "8000", "9000", "",
            "10000",
        ]);

        assert_eq!("24000", part1(input));
    }
}
